package com.example.demo.consumer;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.QueueName;
import com.example.demo.model.Order;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaderMapper;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * 订单消费端
 *
 * @author xushun
 * @email 505232797@qq.com
 * @date 2019/1/21 0:05
 */
@Component
@Slf4j
public class OrderReceiver {
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QueueName.ORDER + "_queue"),
            exchange = @Exchange(name = QueueName.ORDER, type = ExchangeTypes.FANOUT)
    ))
    @RabbitHandler
    public void onOrderMsg(@Payload Order order, @Headers Map<String, Object> headers, Channel channel, Message message) throws IOException {
        //消费者操作
        log.info("headers: {}", JSON.toJSONString(headers));
        log.info("message: {}", JSON.toJSONString(message));
        Random random = new Random();
        if (random.nextBoolean()) {
            log.info("消息处理失败");
            throw new RuntimeException("订单处理失败");
        }
        log.info("订单内容：{}", JSON.toJSONString(order));
        channel.basicAck(Long.valueOf(headers.get(AmqpHeaders.DELIVERY_TAG).toString()), false);
        log.info("订单处理成功");
    }
}
